<script setup lang="ts">
import { ref, onMounted, inject } from 'vue'
import { get, post } from '@/utils/service'
import { VUE_APP_BASE_API, SESSION_LAST_CODE, SESSION_MEMBER_INFO } from '@/utils/baseConfig'
import { useRoute } from 'vue-router'
import { showNotify } from 'vant' // 可选：根据你的UI库引入提示组件，如 Element-UI, Vant 等
import regProtocol from '@/components/regProtocol.vue'
function onClickLeft() {
  window.history.back()
}
const router = useRoute()
const redirect = router.query.redirect as string
const custName = ref('')
const codeNum = ref('')
const groupChecked = ref([])
const member = ref(
  localStorage.getItem(SESSION_MEMBER_INFO + localStorage.getItem(SESSION_LAST_CODE)),
)
const mobilePhone = ref('')
const entepriseColumns = ref([])
const loadingStatus = ref(false)
const showPopProtocalState = ref(false)
//门店选择器
const resultEnterpriseName = ref('')
const enterpriseValue = ref([])
const showEnterprisePicker = ref(false)
const valCodeModel = ref({ load: true, butText: '获取验证码', sendStatus: 1, delay: 60 })
onMounted(async () => {
  try {
    queryEnterprise()
  } catch (error) {
    console.log('onMounted error:' + error)
  }
})
function onEnterpriseConfirm(selectedValues: {}) {
  resultEnterpriseName.value = selectedValues.selectedOptions[0].text
  enterpriseValue.value.push(selectedValues.selectedOptions[0].value)
  showEnterprisePicker.value = false
}

// 校验函数返回 true 表示校验通过，false 表示不通过

function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  console.log('submit', values)
  loadingStatus.value = true // 显示加载状态
  try {
    values.enterpriseId = enterpriseValue.value[0] || ''
    values.name = custName.value || ''
    values.dbid = member.value == null ? -1 : member.value.dbid || -1
    post('/memberWechatNew/saveMemAuth', values).then((res) => {
      if (res.code === 0) {
        showNotify({ type: 'success', message: res.msg + '页面即将跳转...', duration: 3000 })
        const code = localStorage.getItem(SESSION_LAST_CODE)
        localStorage.setItem(SESSION_MEMBER_INFO + code, JSON.stringify(res.data))
        setTimeout(() => {
          window.location.href = redirect || '/'
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function queryEnterprise() {
  get('/enterpriseWechatNew/queryWechatSelect', {}).then((res) => {
    entepriseColumns.value = []
    if (res.code === 0) {
      const data = res.data
      entepriseColumns.value.push(data)
    }
  })
}
function phoneValidator() {
  const state = /^1\d{10}$/.test(mobilePhone.value)
  if (state) {
    valCodeModel.value.load = false
  } else {
    valCodeModel.value.load = true
  }
  return state
}
function codeValidator() {
  return /^[0-9]{4}$/.test(codeNum.value)
}
function nameValidator() {
  return /^[\u4e00-\u9fa5]{2,10}$/.test(custName.value)
}
function sendMobileMessage() {
  valCodeModel.value.load = true
  valCodeModel.value.butText = '发送中...'
  let delay = valCodeModel.value.delay
  get('/memberWechatNew/sendMobileMessage', { mobilePhone: mobilePhone.value }).then((res) => {
    if (res.code === 0) {
      showNotify({ type: 'success', message: '验证码已发送，请注意查收', duration: 3000 })
      valCodeModel.value.sendStatus = 2
      delay--
      valCodeModel.value.butText = delay + 's后重新获取'
      //最后的innerHTML不能丢，否则delay为一个对象
      if (delay > 0) {
        const timeInt = setInterval(() => {
          valCodeModel.value.butText = delay + 's后重新获取'
          delay--
          if (delay <= 0) {
            clearInterval(timeInt)
            valCodeModel.value.load = false
            valCodeModel.value.sendStatus = 1
            valCodeModel.value.butText = '获取验证码'
            valCodeModel.value.delay = 60
          }
        }, 1000)
      }
    } else {
      showNotify({ type: 'danger', message: res.msg })
      valCodeModel.value.butText = '获取验证码'
    }
  })
}
function showRegProtocol() {
  const selected = groupChecked.value
  if (selected == null || selected.length == 0) {
    showNotify({ type: 'danger', message: '请勾选会员注册协议' })
    return
  } else {
    showPopProtocalState.value = true
  }
}
</script>
<template>
  <van-nav-bar title="会员注册" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div class="mainContent">
    <div style="margin: auto 0; text-align: center; padding: 40px 20px; width: 100%">
      <van-image
        width="5rem"
        height="5rem"
        :src="VUE_APP_BASE_API + '/images/vue/myCarMaster.png'"
        position="center"
      />
    </div>
    <van-form @failed="onFailed" @submit="submitFrm">
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="resultEnterpriseName"
          is-link
          required="true"
          readonly
          name="enterpriseName"
          label="门店"
          placeholder="点击选择门店"
          @click="showEnterprisePicker = true"
          :rules="[{ required: true, message: '请选择门店' }]"
        />
        <van-popup :show="showEnterprisePicker" destroy-on-close position="bottom">
          <van-picker
            :columns="entepriseColumns"
            :model-value="enterpriseValue"
            @confirm="onEnterpriseConfirm"
            @cancel="showEnterprisePicker = false"
          />
        </van-popup>
        <van-field
          v-model="custName"
          required="true"
          label="姓名"
          name="custName"
          placeholder="姓名"
          :rules="[
            { required: true, message: '请填写姓名' },
            { validator: nameValidator, message: '请输入姓名,2-10个中文字符' },
          ]"
        />
        <van-field
          v-model="mobilePhone"
          label="联系电话"
          required="true"
          name="mobilePhone"
          placeholder="联系电话"
          type="tel"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { validator: phoneValidator, message: '请输入正确的手机号格式', trigger: 'onChange' },
          ]"
        />
        <van-field
          required="true"
          v-model="codeNum"
          center
          clearable
          name="codeNum"
          type="number"
          label="短信验证码"
          placeholder="请输入短信验证码"
          :rules="[
            { required: true, message: '请输入4位验证码' },
            { validator: codeValidator, message: '请输入4位验证码', trigger: 'onChange' },
          ]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="valCodeModel.load"
              @click="sendMobileMessage"
              >{{ valCodeModel.butText }}</van-button
            >
          </template>
        </van-field>
        <van-field
          name="checkboxGroup"
          label="  "
          :rules="[{ required: true, message: '请勾选会员注册协议' }]"
        >
          <template #input>
            <van-checkbox-group v-model="groupChecked" direction="horizontal" showBottom>
              <van-checkbox name="1" shape="square" @click="showRegProtocol" checked-color="#c82030"
                >会员注册协议</van-checkbox
              >
            </van-checkbox-group>
          </template>
        </van-field>
      </van-cell-group>
      <br />
      <br />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          :loading="loadingStatus"
          loading-type="spinner"
          loading-text="提交中..."
          native-type="submit"
        >
          注册
        </van-button>
      </div>
    </van-form>
  </div>
  <van-popup
    v-model:show="showPopProtocalState"
    closeable
    position="bottom"
    :style="{ height: '90%' }"
  >
    <regProtocol></regProtocol>
  </van-popup>
</template>

<style>
.van-checkbox__label {
  color: var(--main-color);
  font-size: 14px;
  font-weight: 600;
}
</style>
